import { derived, get as getVal } from "svelte/store";
import { makeTicker$, type NextTick } from "./time"

export const makeCounter$ = (tick: number) => {
	const start = new Date();
	const ticker$ = makeTicker$(tick);
	return derived(ticker$, ($ticker$) => Math.round((+$ticker$ - +start) / 1000));
};



// export const makeCountDown$ = (tick: number, max: number, next: NextTick) => {
// 	const start = new Date();
// 	const ticker = makeTicker$(tick);
// 	let countdown$ = derived(ticker, ($ticker) => max - Math.round((+$ticker - +start) / 1000));
// 	let unsub: Unsubscriber = () => {};
// 	unsub = countdown$.subscribe((v) => {
//     if (!next(v)) {
//       unsub();
//     }
// 	});
// 	return countdown$;
// };

export const countDown =  (tick: number, max: number, next: NextTick) => {
	const start = new Date();
	const ticker$ = makeTicker$(tick);
	let countdown$ = derived(ticker$, ($ticker$) => max - Math.round((+$ticker$ - +start) / 1000), 0);
	let unsub = countdown$.subscribe((v) => {
		console.log('v=>', v)
		if (v < 0) {
			unsub();
		} else {
			next(v)
		}
	});
	return unsub;
}